package view;

import com.mysql.jdbc.StringUtils;
import com.sun.java.swing.action.AlignCenterAction;
import dao.BookDao;
import dao.bdetailDao;
//import jdk.internal.joptsimple.internal.Strings;
import model.Book;
import model.BorrowDetail;
import util.DbUtil;
import util.toolUtil;

import javax.swing.*;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.TooManyListenersException;
import java.util.function.BinaryOperator;

public class UserMenuFrm {


    private BookDao bookDao;
    private DbUtil dbUtil;
    private JFrame jf;
    private Connection con;
    private JPanel borrowPanel;
    private JPanel returnPanel;
    private toolUtil toolUtil;

    private bdetailDao bdtailDao;
    DefaultTableModel model;

    String [][] dates ={};
    String [][] BookDates={};

    DefaultTableModel BookModel;
    String [] title ={"书名","书id","状态","借书时间","还书时间"};
    String [] BookTitle = {"编号","书名","类型","作者","描述"};

    public UserMenuFrm(){



        // JPanel panel=new JPanel();

        toolUtil=new toolUtil();

        bdtailDao=new bdetailDao();

        bookDao=new BookDao();

        jf=new JFrame("图书管理");
        jf.setBackground(Color.BLUE);

        jf.getContentPane().setFont(new Font("幼圆",Font.BOLD,14));

        jf.setBounds(500,250,500,500);

        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // jf.getContentPane().setLayout(null);

        jf.setLayout(new BorderLayout());

        jf.setVisible(true);




        JMenuBar jMenuBar=new JMenuBar();


        JMenu menu1=new JMenu("功能");
        // JMenu menu2=new JMenu("还书");
        JMenuItem item1=new JMenuItem("借书");
        JMenuItem item2=new JMenuItem("还书");
        menu1.add(item1);
        menu1.add(item2);

        jMenuBar.add(menu1);


        JMenu menu2=new JMenu("设置");
        // JMenu menu2=new JMenu("还书");
        JMenuItem item21=new JMenuItem("设置1");
        JMenuItem item22=new JMenuItem("设置2");
        menu2.add(item21);
        menu2.add(item22);

        jMenuBar.add(menu2);


        JMenu menu3=new JMenu("帮助");
        // JMenu menu2=new JMenu("还书");
        JMenuItem item31=new JMenuItem("帮助1");
        JMenuItem item32=new JMenuItem("帮助1");
        menu3.add(item31);
        menu3.add(item32);

        jMenuBar.add(menu3);




        JMenu menu4=new JMenu("通知");
        // JMenu menu2=new JMenu("还书");
        JMenuItem item41=new JMenuItem("帮助1");
        JMenuItem item42=new JMenuItem("帮助1");
        menu4.add(item41);
        menu4.add(item42);

        jMenuBar.add(menu4);

        jMenuBar.setBackground(Color.PINK);

        JMenu menu5=new JMenu("消息");
        // JMenu menu2=new JMenu("还书");
        JMenuItem item51=new JMenuItem("帮助1");
        JMenuItem item52=new JMenuItem("帮助1");
        menu5.add(item51);
        menu5.add(item52);

        jMenuBar.add(menu5);












        // jMenuBar.add(menu2);
        jf.setJMenuBar(jMenuBar);

        // 创建借书页面
        borrowPanel = new JPanel();
        // borrowPanel.setBounds(20, 50, 300, 467);
        borrowPanel.setVisible(true);
        Button ba1=new Button();
        borrowPanel.add(ba1);

        borrowPanel.setBackground(Color.RED);

        borrowPanel.setBorder(new TitledBorder(null,"\u4E66\u7C4D\u4FE1\u606F",TitledBorder.LEADING,TitledBorder.TOP,null,Color.BLACK.RED));
        borrowPanel.setBounds(0,50,651,346);

        // jf.getContentPane().add(panel_2);
        borrowPanel.setLayout(null);

        JComboBox<String> comboBox =new JComboBox<>();
        comboBox.setFont(new Font("幼圆",Font.BOLD,15));
        comboBox.setBounds(123,26,109,24);
        comboBox.addItem("书籍名称");
        comboBox.addItem("书籍作者");

        borrowPanel.add(comboBox);

        JTextField textField_1 =new JTextField();
        textField_1.setColumns(10);
        textField_1.setBounds(252,23,135,27);
        borrowPanel.add(textField_1);

        JButton button_1=new JButton("查询");
        button_1.setFont(new Font("幼圆",Font.BOLD,16));
        button_1.setBounds(408,20,93,33);
        borrowPanel.add(button_1);

        JButton button_2=new JButton("返回");
        button_2.setFont(new Font("幼圆",Font.BOLD,16));
        button_2.setBounds(530,20,93,33);
        borrowPanel.add(button_2);




        BookModel =new DefaultTableModel(BookDates,BookTitle);
        JTable BookTable =new JTable(BookModel);

        try {
            putDates(new Book());
        } catch (Exception e) {
            e.printStackTrace();
        }




        JScrollPane jScrollPane=new JScrollPane();
        jScrollPane.setBounds(22,74,607,250);
        jScrollPane.setViewportView(BookTable);
        borrowPanel.add(jScrollPane);

        jf.getContentPane().add(borrowPanel);


        JPanel panel2=new JPanel();
        panel2.setVisible(true);
        panel2.setBackground(Color.PINK);
        panel2.setBorder(new TitledBorder(null,"\u501F\u4E66",TitledBorder.LEADING,TitledBorder.TOP,null,Color.RED));
        panel2.setBounds(0,400,645,87);
        panel2.setLayout(null);
        JLabel label=new JLabel("编号:");
        label.setBounds(68,31,48,33);
        panel2.add(label);
        JTextField textField3=new JTextField();
        textField3.setEditable(true);
        textField3.setColumns(10);
        textField3.setBounds(126,34,135,27);
        panel2.add(textField3);

        JLabel label1=new JLabel("书名");
        label1.setFont(new Font("Dialog",Font.BOLD,15));
        label1.setBounds(281,34,48,33);
        panel2.add(label1);
        JTextField textField=new JTextField();
        textField.setEditable(true);
        textField.setColumns(10);
        textField.setBounds(339,34,135,27);
        panel2.add(textField);

        JButton button=new JButton("借书");
        button.setFont(new Font("Dialog",Font.BOLD,16));
        button.setBounds(495,31,80,33);
        panel2.add(button);




        jf.getContentPane().add(panel2);



        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {

                String number = textField3.getText();
                String name = textField.getText();


                if(StringUtils.isNullOrEmpty(name)||StringUtils.isNullOrEmpty(number)){
                    JOptionPane.showMessageDialog(null,"检索信息不能为空","重新输入",JOptionPane.WARNING_MESSAGE);

                    return;
                }

                BorrowDetail borrowDetail=new BorrowDetail();
                borrowDetail.setUserId(LoginFrm.currentUser.getUserId());
                borrowDetail.setBookId(Integer.parseInt(number));
                borrowDetail.setStatus(1);
                borrowDetail.setBorrowTime(Long.parseLong(""+LocalDateTime.now().getNano()));

                Connection con=null;



                try {
                    con = dbUtil.getConnection();
                    ResultSet list = bdtailDao.list(con, borrowDetail);
                    while (list.next()) {

                        JOptionPane.showMessageDialog(null, "该书已经再借,请先还再借");
                        return;
                    }
                    int i = bdtailDao.add(con, borrowDetail);
                    if (i == 1) {
                        JOptionPane.showMessageDialog(null, "借书成功");
                        putDates2(new BorrowDetail());

                    } else {
                        JOptionPane.showMessageDialog(null, "借书失败");
                    }


                }catch (Exception e2){
                    // JOptionPane.showMessageDialog(null,);
                    e2.printStackTrace();
                }

            }
        });

        button_1.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String s = comboBox.getSelectedItem().toString();
                String text = textField_1.getText();

                Book queryBook=new Book();

                if(s.equals("书籍名称")){
                    queryBook.setBookName(text);
                }else if(s.equals("书籍作者")){
                    queryBook.setAuthor(text);
                }

                try {
                    putDates(queryBook);
                } catch (Exception exception) {
                    exception.printStackTrace();
                }


            }
        });


        button_2.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                dbUtil=new DbUtil();
                try {
                    con=dbUtil.getConnection();
                } catch (Exception exception) {
                    exception.printStackTrace();
                }

                    List<Book> list = null;
                    try {
                        list = bookDao.selectAll(con);
                    } catch (SQLException throwables) {
                        throwables.printStackTrace();
                    }

                    BookDates=new String[list.size()][5];


                    for (int i = 0; i < BookDates.length; i++) {
                        BookDates[i][0]=list.get(i).getBookId().toString();

                        BookDates[i][1]=list.get(i).getBookName().toString();

                        BookDates[i][2]=list.get(i).getBookTypeId().toString();

                        BookDates[i][3]=list.get(i).getAuthor().toString();

                        BookDates[i][4]=list.get(i).getRemark().toString();
                    }


                    for (String[] bookDate : BookDates) {
                        for (String s : bookDate) {
                            System.out.println(s);
                        }
                    }

                    BookModel.setDataVector(BookDates, BookTitle);

                }
        });

        // 创建还书页面
        returnPanel = new JPanel();
        returnPanel.setBounds(0, 0, 500, 467);
        returnPanel.setVisible(false);

        returnPanel.setVisible(false);


        returnPanel.setBorder (new
                TitledBorder(UIManager.getBorder ("TitledBorder.border"),
                "\u501F\u9605\u4FE1\u606F",TitledBorder.LEADING,TitledBorder.TOP, null, new Color(255,0,0,0)));
        returnPanel.setBounds(23,48,651,239);





        model =new DefaultTableModel(dates,title);
        JTable table=new JTable();
        table.setModel(model);


        try {
            putDates2(new BorrowDetail());
        } catch (Exception e) {
            e.printStackTrace();
        }


        returnPanel.setLayout(null);
        JScrollPane jScrollPane1=new JScrollPane();
        jScrollPane1.setBounds(20,22,607,188);
        jScrollPane1.setViewportView(table);
        returnPanel.add(jScrollPane1);

        jf.getContentPane().add(returnPanel);




        JPanel panel=new JPanel();
        panel.setVisible(false);
        panel.setBounds(23,294,651,70);
        panel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"),"\u8FD8\u4E66",TitledBorder.LEADING,TitledBorder.TOP,null,new Color(255,0,0)));
        panel.setLayout(null);
        JLabel label2=new JLabel("书编号");
        label2.setBounds(90,25,51,27);
        panel.add(label2);
        JTextField textField1=new JTextField();
        textField1.setBounds(145,28,116,24);
        panel.add(textField1);
        textField1.setColumns(10);
        JButton button1=new JButton("还书");
        button1.setBounds(299,25,85,31);
        panel.add(button1);


        jf.getContentPane().add(panel);

        button1.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {



                dbUtil=new DbUtil();
                try {
                    con=dbUtil.getConnection();
                } catch (Exception exception) {
                    exception.printStackTrace();
                }

                String text = textField1.getText();


               try {
                   bdtailDao.removeByBookId(con, text);
               }catch (Exception ee){
                   JOptionPane.showMessageDialog(null,"数据操作异常","异常通知",JOptionPane.WARNING_MESSAGE);

               }
                try {
                    putDates2(new BorrowDetail());
                } catch (Exception exception) {
                    exception.printStackTrace();
                }


                System.out.println("还书");

            }
        });


        // 借书菜单项

        item1.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("zuoyong");
                borrowPanel.setVisible(true);
                panel2.setVisible(true);
                returnPanel.setVisible(false);
                panel.setVisible(false);
            }
        });


        // 还书菜单项
        item2.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                borrowPanel.setVisible(false);
                panel2.setVisible(false);
                returnPanel.setVisible(true);
                panel.setVisible(true);
            }
        });

    }

    private void putDates2(BorrowDetail borrowDetail) throws  Exception {



        dbUtil=new DbUtil();
        con=dbUtil.getConnection();

      List<BorrowDetail> list=  bdtailDao.selectAll(con);

      dates=new String[list.size()][5];
        List<Book> list1 = bookDao.selectAll(con);


        for (int i = 0; i < dates.length; i++) {

            dates[i][1]=list.get(i).getBookId().toString();
            dates[i][0]= list1.get(
                    list.get(i).getBookId()).getBookName();

            dates[i][2]=list.get(i).getStatus().toString();

            LocalDateTime now = LocalDateTime.now();
            int nano = LocalDateTime.now().getNano();
            long l = nano - list.get(i).getBorrowTime();

            Instant instant = Instant.ofEpochMilli(l);
            LocalDateTime dateTime = instant.atZone(ZoneId.systemDefault()).toLocalDateTime();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String formattedDateTime = dateTime.format(formatter);


            dates[i][3]=formattedDateTime;




            dates[i][4]=list.get(i).getReturnTime().toString();


        }

        model.setDataVector(dates,title);

    }

    private void putDates(Book book) throws Exception {

        dbUtil=new DbUtil();
        con=dbUtil.getConnection();

        if(Objects.isNull(book.getAuthor())&&Objects.isNull(book.getBookName())){

            List<Book> list = bookDao.selectAll(con);

            BookDates=new String[list.size()][5];


            for (int i = 0; i < BookDates.length; i++) {
                       BookDates[i][0]=list.get(i).getBookId().toString();

                       BookDates[i][1]=list.get(i).getBookName().toString();

                       BookDates[i][2]=list.get(i).getBookTypeId().toString();

                       BookDates[i][3]=list.get(i).getAuthor().toString();

                        BookDates[i][4]=list.get(i).getRemark().toString();
            }


            for (String[] bookDate : BookDates) {
                for (String s : bookDate) {
                    System.out.println(s);
                }
            }

            BookModel.setDataVector(BookDates, BookTitle);



        }else{

            if(!Objects.isNull(book.getAuthor())){

                List<Book> list =   bookDao.selectByBook(con,book);
                BookDates=new String[list.size()][5];



                for (int i = 0; i < BookDates.length; i++) {
                    BookDates[i][0] = list.get(i).getBookId().toString();
                    BookDates[i][1] = list.get(i).getBookName().toString();
                    BookDates[i][2] = list.get(i).getBookTypeId().toString();
                    BookDates[i][3] = list.get(i).getAuthor().toString();
                    BookDates[i][4] = list.get(i).getRemark().toString();
                }

                for (String[] bookDate : BookDates) {
                    for (String s : bookDate) {
                        System.out.println(s);
                    }
                }
                BookModel.setDataVector(BookDates, BookTitle);

                


            }else if(!Objects.isNull(book.getBookName())){

                List<Book> list =   bookDao.selectByBook(con,book);
                BookDates=new String[list.size()][5];

                for (int i = 0; i < BookDates.length; i++) {
                    BookDates[i][0] = list.get(i).getBookId().toString();
                    BookDates[i][1] = list.get(i).getBookName().toString();
                    BookDates[i][2] = list.get(i).getBookTypeId().toString();
                    BookDates[i][3] = list.get(i).getAuthor().toString();
                    BookDates[i][4] = list.get(i).getRemark().toString();
                }

                for (String[] bookDate : BookDates) {
                    for (String s : bookDate) {
                        System.out.println(s);
                    }
                    // System.out.println("------------------------------");
                }


            }

            BookModel.setDataVector(BookDates, BookTitle);


        }

    }

    public static void main(String[] args) {
        new UserMenuFrm();



    }





}























